package com.lihaogn.sell.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lihaogn.sell.dto.PreRecomFoodDto;
import com.lihaogn.sell.entity.Food;
import com.lihaogn.sell.mapper.FoodMapper;
import com.lihaogn.sell.service.ProductService;
import com.lihaogn.sell.vo.FoodVo;
import com.lihaogn.sell.vo.ListVo;
import com.lihaogn.sell.vo.SearchPageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: ProductServiceImpl
 * @Description: TODO
 * @Author: lihao
 * @Date: 2019-05-25 09:14
 * @Version: 1.0
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    FoodMapper foodMapper;

    @Override
    public List<String> queryRecom(String userId, Integer peoples) {

        List<String> recomFoods = new ArrayList<>();
        int vegeTargetNum = 0;
        int unVegeTargetNum = 0;

        // 1 确定推荐菜品数目
        int recomNum = peoples * 3 / 2;
        // ==> 选择至少1/3的素菜
        int vegeNum = (int) Math.ceil((double) recomNum / 3);
        // ==> 确定非素菜数目
        int unVegeNum = recomNum - vegeNum;

        // 2 根据条件填充推荐菜品列表

        // 2.1 查询到预推荐的菜品
        List<PreRecomFoodDto> preRecomFoods = foodMapper.queryRecom(userId);
        // 2.2 筛选预推荐中的素菜
        for (PreRecomFoodDto food : preRecomFoods) {
            if ("599640e3-778e-418f-8ad0-828bda0abcdc".equals(food.getFtcId())) {
                recomFoods.add(food.getFoodId());
                vegeTargetNum++;
                if (vegeTargetNum >= vegeNum) {
                    break;
                }
            } else {
                recomFoods.add(food.getFoodId());
                unVegeTargetNum++;
                if (unVegeTargetNum >= unVegeNum) {
                    break;
                }
            }
        }
        // ==> 素菜未达到规定的数目
        if (vegeTargetNum < vegeNum) {
            // 去素菜排行中找到没有被预推荐的菜品
            List<String> topVeges = foodMapper.queryTopVege();
            for (String foodId : topVeges) {
                if (!recomFoods.contains(foodId)) {
                    recomFoods.add(foodId);
                    vegeTargetNum++;
                    if (vegeTargetNum >= vegeNum) {
                        break;
                    }
                }
            }
        }
        // ==> 非素菜未到达规定的数目
        if (unVegeTargetNum < unVegeNum) {
            // 去非素菜排行中找到没有被预推荐的菜品
            List<String> topUnVeges = foodMapper.queryTopUnVege();
            for (String foodId : topUnVeges) {
                if (!recomFoods.contains(foodId)) {
                    recomFoods.add(foodId);
                    unVegeTargetNum++;
                    if (unVegeTargetNum >= unVegeNum) {
                        break;
                    }
                }
            }
        }


        return recomFoods;
    }

    @Override
    public List<Food> getAllFood() {
        return foodMapper.queryAllFood();
    }

    // ====== 查询 ======
    @Override
    public ListVo searchFood(SearchPageVo searchPageVo) {
        Map<String, Object> queryMap = new HashMap<>();
        ListVo listVo = new ListVo();

        List<FoodVo> foodList;
        int searchCount;

        Integer limit = searchPageVo.getLimit();
        Integer page = (searchPageVo.getPage() - 1) * limit;
        String name = searchPageVo.getName();
        String start = searchPageVo.getStart();
        String end = searchPageVo.getEnd();

        queryMap.put("page", page);
        queryMap.put("size", limit);

        if (!"".equals(name)) {
            // name不为空，按照name查找
            FoodVo food = foodMapper.queryFoodByName(name);
            foodList = new ArrayList<>();
            foodList.add(food);

            listVo.setCode(0);
            listVo.setMsg("success");
            listVo.setCount(1);
            listVo.setData(foodList);

            return listVo;
        } else if ("".equals(start)) {
            // 开始日期为空，则查找结束日期前的
            queryMap.put("end", end);
            foodList = foodMapper.querytFoodByDateForPage(queryMap);
            searchCount = foodMapper.queryCountByDate(queryMap);
        } else if ("".equals(end)) {
            // 结束日期为空，则查找开始日期后的
            queryMap.put("start", start);
            foodList = foodMapper.querytFoodByDateForPage(queryMap);
            searchCount = foodMapper.queryCountByDate(queryMap);
        } else {
            // 查找开始日期到结束日期的
            queryMap.put("end", end);
            queryMap.put("start", start);
            foodList = foodMapper.querytFoodByDateForPage(queryMap);
            searchCount = foodMapper.queryCountByDate(queryMap);
        }

        listVo.setCode(0);
        listVo.setMsg("success");
        listVo.setCount(searchCount);
        listVo.setData(foodList);

        return listVo;
    }

    @Override
    public Food getOneFoodById(String foodId) {
        return foodMapper.queryOneFoodById(foodId);
    }

    @Override
    public List<FoodVo> getAllFoodForPage(String page, String size) {

        Map<String, Integer> pageMap = new HashMap<>();

        int pageOne = Integer.valueOf(page);
        int pageSize = Integer.valueOf(size);
        int start = (pageOne - 1) * pageSize;

        pageMap.put("page", start);
        pageMap.put("size", pageSize);

        List<FoodVo> foodList = foodMapper.queryFoodForPage(pageMap);
        return foodList;
    }

    @Override
    public int getFoodRowsCount() {
        return foodMapper.queryFoodRowsCount();
    }

    @Override
    public int queryExistFoodName(String name) {
        return foodMapper.queryExistFoodName(name);
    }

    // ====== 添加 ======

    @Override
    public int addOneFood(Food food) {
        return foodMapper.insertOneFood(food);
    }

    // ====== 更新 ======

    @Override
    public int updateOneFood(Food food) {
        return foodMapper.updateOneFoodById(food);
    }

    // ====== 删除 ======

    @Override
    public int deleteOneFood(String foodId) {
        return foodMapper.deleteOneFoodById(foodId);
    }

    @Override
    public int deleteMultiFood(HttpServletRequest request) {
        // 记录删除的个数
        int num;
        BufferedReader reader;

        try {
            reader = request.getReader();

            StringBuffer res = new StringBuffer();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            ObjectMapper objectMapper = new ObjectMapper();
            ArrayList<String> idList = objectMapper.readValue(res.toString(), ArrayList.class);

            HashMap<String, Object> map = new HashMap<>();
            map.put("idList", idList);

            num = foodMapper.deleteMultiFood(map);
            if (num == idList.size()) {
                return 1;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
